using System.Windows;
using CommunityToolkit.Mvvm.Messaging;

namespace DYH.Extensions.CAD.Wpf;

/// <summary>
/// Wpf扩展工具
/// </summary>
public static class WpfTool
{
    /// <summary>
    /// 关闭引用了自身的窗口
    /// </summary>
    /// <param name="viewModel">视图模型</param>
    public static void CloseSelfWindow(this ObservableObject viewModel)
    {
        WeakReferenceMessenger.Default.Send(new CloseWindowMessage(viewModel));
    }

    /// <summary>
    /// 注册关闭窗口消息
    /// </summary>
    /// <param name="window">窗口</param>
    public static void RegisterCloseMessage(this Window window)
    {
        WeakReferenceMessenger.Default.Register<CloseWindowMessage>(window, CloseWindowHandler);
    }

    private static void CloseWindowHandler(object recipient, CloseWindowMessage message)
    {
        if (recipient is not Window window || !message.ViewModelRef.TryGetTarget(out var viewModel))
            return;
        if (window.DataContext == viewModel)
            return;
        window.Close();
    }
}